<template>
  <div class="personnel-import">
    <div class="page-title">数据导入</div>

    <el-row :gutter="20">
      <el-col :xs="24" :lg="16">
        <div class="page-card">
          <h3>上传 Excel 文件</h3>
          
          <el-alert
            title="导入说明"
            type="info"
            :closable="false"
            style="margin: 20px 0"
          >
            <p>1. 请先下载 Excel 模板，按照模板格式填写数据</p>
            <p>2. 姓名为必填字段，其他字段选填</p>
            <p>3. 支持 .xlsx 和 .xls 格式，文件大小不超过 10MB</p>
            <p>4. 如果填写了数据源字段，系统会自动跳过已存在相同数据源的记录</p>
          </el-alert>

          <el-upload
            ref="uploadRef"
            class="upload-box"
            drag
            :auto-upload="false"
            :limit="1"
            accept=".xlsx,.xls"
            :on-change="handleFileChange"
            :on-exceed="handleExceed"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 xlsx/xls 文件，且不超过 10MB
              </div>
            </template>
          </el-upload>

          <div class="action-buttons">
            <el-button
              type="primary"
              :icon="Download"
              @click="handleDownloadTemplate"
            >
              下载模板
            </el-button>
            <el-button
              type="success"
              :icon="Upload"
              :loading="uploading"
              :disabled="!currentFile"
              @click="handleUpload"
            >
              开始导入
            </el-button>
            <el-button @click="handleClear">清除</el-button>
          </div>

          <!-- 导入结果 -->
          <el-alert
            v-if="importResult"
            :title="importResult.success ? '✓ 导入完成' : '✗ 导入失败'"
            :type="getResultType(importResult)"
            :closable="false"
            style="margin-top: 20px"
          >
            <div v-if="importResult.success">
              <p>总行数: {{ importResult.totalRows }}</p>
              <p>成功: {{ importResult.successCount }}</p>
              <p v-if="importResult.skipCount > 0" style="color: #e6a23c; font-weight: bold;">
                跳过: {{ importResult.skipCount }}（数据源已存在）
              </p>
              <p v-if="importResult.failCount > 0" style="color: #f56c6c; font-weight: bold;">
                失败: {{ importResult.failCount }}
              </p>
              
              <!-- 跳过记录详情 -->
              <div v-if="importResult.skipCount > 0 && importResult.skipped && importResult.skipped.length > 0" style="margin-top: 15px;">
                <el-divider content-position="left">跳过记录详情</el-divider>
                <el-table
                  :data="importResult.skipped"
                  max-height="300"
                  stripe
                  style="width: 100%"
                >
                  <el-table-column prop="row" label="行号" width="80" />
                  <el-table-column prop="name" label="姓名" width="150" />
                  <el-table-column label="数据源" min-width="200">
                    <template #default="{ row }">
                      <span style="font-size: 12px;">{{ row.data_source }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="跳过原因" width="150">
                    <template #default="{ row }">
                      <el-tag type="warning" size="small">{{ row.reason }}</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              
              <!-- 失败详情 -->
              <div v-if="importResult.failCount > 0 && importResult.errors && importResult.errors.length > 0" style="margin-top: 15px;">
                <el-divider content-position="left">失败记录详情</el-divider>
                <el-table
                  :data="importResult.errors"
                  max-height="300"
                  stripe
                  style="width: 100%"
                >
                  <el-table-column prop="row" label="行号" width="80" />
                  <el-table-column label="数据" min-width="200">
                    <template #default="{ row }">
                      <div style="font-size: 12px;">
                        <div v-if="row.data">
                          <span v-if="row.data.name">姓名: {{ row.data.name }}</span>
                          <span v-if="row.data.position"> | 岗位: {{ row.data.position }}</span>
                        </div>
                        <div v-else style="color: #909399;">数据为空</div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="失败原因" min-width="200">
                    <template #default="{ row }">
                      <el-tag type="danger" size="small">{{ row.error }}</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            <div v-else>
              <p>{{ importResult.message }}</p>
              <!-- 验证错误详情 -->
              <div v-if="importResult.errors && importResult.errors.length > 0" style="margin-top: 15px;">
                <el-divider content-position="left">错误详情</el-divider>
                <el-table
                  :data="importResult.errors"
                  max-height="300"
                  stripe
                  style="width: 100%"
                >
                  <el-table-column prop="row" label="行号" width="80" />
                  <el-table-column label="错误信息">
                    <template #default="{ row }">
                      <div v-for="(err, idx) in row.errors" :key="idx">
                        <el-tag type="danger" size="small" style="margin: 2px;">{{ err }}</el-tag>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-alert>
        </div>
      </el-col>

      <el-col :xs="24" :lg="8">
        <div class="page-card">
          <h3>导入历史</h3>
          <el-empty
            description="暂无导入记录"
            :image-size="120"
          />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, Download, Upload } from '@element-plus/icons-vue'
import { personnelApi } from '@/api/personnel'

const uploadRef = ref()
const currentFile = ref(null)
const uploading = ref(false)
const importResult = ref(null)

// 文件变化
const handleFileChange = (file) => {
  currentFile.value = file.raw
  importResult.value = null
}

// 超出限制
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件')
}

// 下载模板
const handleDownloadTemplate = () => {
  window.open(personnelApi.downloadTemplate(), '_blank')
  ElMessage.success('开始下载模板')
}

// 上传文件
const handleUpload = async () => {
  if (!currentFile.value) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  uploading.value = true
  importResult.value = null

  try {
    const result = await personnelApi.uploadExcel(currentFile.value)
    importResult.value = result

    if (result.success) {
      ElMessage.success('导入成功')
      handleClear()
    } else {
      ElMessage.error(result.message || '导入失败')
    }
  } catch (error) {
    ElMessage.error('导入失败: ' + error.message)
  } finally {
    uploading.value = false
  }
}

// 清除
const handleClear = () => {
  currentFile.value = null
  uploadRef.value?.clearFiles()
}

// 获取结果类型
const getResultType = (result) => {
  if (!result.success) return 'error'
  if (result.failCount > 0) return 'warning'
  return 'success'
}
</script>

<style lang="scss" scoped>
.personnel-import {
  .upload-box {
    margin: 20px 0;
  }

  .action-buttons {
    display: flex;
    gap: 12px;
    margin-top: 20px;
  }

  :deep(.el-alert) {
    p {
      margin: 4px 0;
    }
  }
}
</style>

